import {defineStore} from 'pinia'
import { ref,computed, watch } from 'vue'

export const useCartStore = defineStore('cart',() => {
  const cart = ref([])
  // 购物车添加操作
  const addCartInfo = (item) => {
    const commodity = cart.value.findIndex(ele => ele.id === item.id)
    if (commodity > -1) {
      cart.value[commodity].count += item.count
    } else {
      cart.value.push(item)
    }
  }
  // 修改选中状态
  const radioChange = (id) => {
    const a = cart.value.findIndex(item => item.id === id)
    cart.value[a].state = cart.value[a].state === 2? 1 : 2
  }
  // 修改商品数量
  const changeNum = (id,num) => {
    const a = cart.value.find(item => item.id === id)
    a.count = num
  }
  // 删除商品
  const delCart = (id) => {
    const a = cart.value.findIndex(item => item.id === id)
    cart.value.splice(a,1)
    // cart.value = cart.value.filter(item => item.id !== id)
  }
  // 统计购物车内商品数量
  const cartNum = computed(() => cart.value.reduce((a,b) => a + b.count,0))
  const cartNum2 = computed(() => JSON.parse(uni.getStorageSync('cart')).reduce((a,b) => a + b.count,0))
  
  // 购物车选中状态价格
  const priceSum = computed(() => cart.value.filter(item => item.state === 1).reduce((a,b) => a + b.price * b.count,0))
  const statesSum = computed(() => cart.value.filter(item => item.state === 1).reduce((a,b) => a + b.count,0))
  watch(statesSum,() => {
    setBage()
  })
  // 全选
  const totalSum = computed(() => cart.value.every(item => item.state === 1))
  // 点击全选
  const clickTotal = (val) => {
    if (val) {
      cart.value.forEach(item => item.state = 1)
    } else {
      cart.value.forEach(item => item.state = 2)
    }
  }
  
  //购物车徽标展示
  const setBage = () => {
    uni.setTabBarBadge({
      index: 2,
      text: cartNum.value + ''
    })
  }
  return {
    cart,
    addCartInfo,
    cartNum,
    cartNum2,
    setBage,
    radioChange,
    changeNum,
    delCart,
    priceSum,
    statesSum,
    totalSum,
    clickTotal
  }
},
{
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value) // [!code warning]
        },
        getItem(key) {
          return uni.getStorageSync(key) // [!code warning]
        },
      },
    },
  },
)